<template>
  <div id="push-index" ref="pushIndex">
    <cs-header v-if="sysNameObj.systemSwitch === 'ON'"></cs-header>
    <tc-header v-else></tc-header>
    <p class="title">我的应用</p>
    <div class="mainconteler">
      <!-- 工具栏 -->
      <div style="padding:15px;background:#fff">
        <el-button type="primary" @click="handleAddApply" size="mini">新建应用</el-button>
      </div>
      <div class="mt10">
        <!-- 表格 -->
        <el-table ref="table" :data="pushIndexData" v-loading="tableLoading"
         style="padding: 0px 20px">
          <el-table-column label="平台" prop="platform"></el-table-column>
          <el-table-column label="名称" prop="appName"></el-table-column>
          <el-table-column label="Access ID" prop="accessId"></el-table-column>
          <el-table-column label="分类" prop="appType">
            <template slot-scope="scope">
              {{devTypesDict[scope.row.appType]}}
            </template>
          </el-table-column>
          <el-table-column label="appKey" prop="appKey"></el-table-column>
          <el-table-column label="secretKey" prop="secretKey"></el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleChangeOperate(scope.row, 'create')">创建推送</el-button>
              <el-button type="text" size="small" @click="handleChangeOperate(scope.row, 'historical')">历史明细</el-button>
              <el-button type="text" size="small" @click="handleChangeOperate(scope.row, 'application')">应用配置</el-button>
            </template>
          </el-table-column>
        </el-table>
      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="totalCount"
          style="padding:20px 5px">
        </el-pagination>
      </div>
    </div>
    <!--------------- 弹框 ---------------->
    <el-dialog
      title="选择平台"
      :visible.sync="dialogVisible"
      @close="handleDialogClose"
      width="60%">
      <el-row :gutter="20" type="flex" justify="center" align="middle">
        <!---- 第一步 ---->
        <el-col :span="14" :offset="4" v-show="act_flag === 0">
          <ul class="plat-list">
            <li :class="{ active:platIndex === '22' }" @click="selectPlat('22')">
              <el-radio v-model="ruleForm.platform"></el-radio>
              <span>IOS</span>
            </li>
            <li :class="{ active:platIndex === '21' }" @click="selectPlat('21')">
              <el-radio v-model="ruleForm.platform"></el-radio>
              <span>Android</span>
            </li>
          </ul>
        </el-col>
        <!---- 第二步 ---->
        <el-col :span="16" :offset="2" v-show="act_flag === 1">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" size="small" label-width="100px" class="demo-ruleForm">
            <el-form-item label="应用名称" prop="appName">
              <el-input v-model="ruleForm.appName"></el-input>
            </el-form-item>
              <span style="color:red;display:inline-block;margin-top:10px;margin-left:22px" v-show="platIndex === '21'">*</span>
            <el-form-item v-show="platIndex === '21'" label="应用包名" prop="appPackageName" style="margin-top:-26px">
              <el-input v-model="ruleForm.appPackageName"></el-input>
            </el-form-item>
            <el-form-item label="所属分类" prop="appType">
              <el-select popper-class="zIndex-popper" v-model="ruleForm.appType">
                <el-option v-for="item in appTypeArr" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="checked">我同意  《信鸽开发者服务协议》</el-checkbox>
            </el-form-item>
          </el-form>
        </el-col>
        <!---- 第三步(Android) ---->
        <el-col :span="16" :offset="2" v-show="act_flag === 2 && platIndex === '21'">
          <el-card class="box-card">
            <ul>
              <li>以下列出的ID以及Key，用于 Android Push SDK 的接入</li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>APP ID</span>
                    <el-tooltip placement="right">
                      <div slot="content">信鸽系统生成的用于标识应用的ID，在调用 PUSH API V3 时需要使用。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.appKey}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>SECRET KEY</span>
                    <el-tooltip placement="right">
                      <div slot="content">用于验证API调用的密钥，用于验证调用的合法性。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.secretKey}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>ACCESS ID</span>
                    <el-tooltip placement="right">
                      <div slot="content">信鸽系统生成的ID，需要配置到客户端SDK中。<br>此外，在调用 PUSH API V2 时也需要使用。（ PUSH API V3 中不再使用）</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.accessId}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>ACCESS KEY</span>
                    <el-tooltip placement="right">
                      <div slot="content">信鸽系统生成的客户端鉴权密钥，与ACCESS ID共同验证以确定调用合法。<br>需要配置到客户端SDK中，无法更换。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.accessKey}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>客户端SDK</span>
                  </el-col>
                  <el-col :span="16"><span>点击下载</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>一键接入指南</span>
                  </el-col>
                  <el-col :span="16"><span>点击查看</span></el-col>
                </el-row>
              </li>
              <li>
                <i class="el-icon-warning"></i> 如果您需要使用「厂商/海外推送通道」，请确认已经按照集成文档中的说明进行集成，避免造成重复发版。
              </li>
            </ul>
          </el-card>
        </el-col>
        <!---- 第三步(IOS) ---->
        <el-col :span="16" :offset="2" v-show="act_flag === 2 && platIndex === '22'">
          <el-card class="box-card">
            <ul>
              <li>与Android推送不同，iOS推送需要上传APNS的Push证书才能正常推送</li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>开发证书</span>
                    <el-tooltip placement="right">
                      <div slot="content">开发证书对应apple的development字样，适用于推送开发环境。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="18">
                      <div>
                        <input type="file" id="file" @change="developfileChange">
                        <el-button type="text" v-show="showonebar" @click="requestDevelop">确认上传</el-button>
                      </div>
                  </el-col>
                </el-row>
                 <span style="margin-left:120px;color:#f4bc00">请上传pem类型的文件</span>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>生产证书</span>
                    <el-tooltip placement="right">
                      <div slot="content">生产证书对应apple的development字样，适用于推送开发环境。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="18">
                      <div>
                        <input type="file" id="filebar" @change="producefileChange">
                        <el-button type="text" v-show="showtwobar" @click="requestProduce">确认上传</el-button>
                      </div>
                  </el-col>
                </el-row>
                 <span style="margin-left:120px;color:#f4bc00">请上传pem类型的文件</span>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>证书教学</span>
                  </el-col>
                  <el-col :span="16"><span>查看视频</span></el-col>
                </el-row>
              </li>
            </ul>
          </el-card>
        </el-col>
        <!---- 第四步(IOS) ---->
        <el-col :span="16" :offset="2" v-show="act_flag === 3 && platIndex === '22'">
          <el-card class="box-card">
            <ul>
              <li>以下列出的ID及Key，用于 iOS Push SDK的接入</li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>APP ID</span>
                    <el-tooltip placement="right">
                      <div slot="content">信鸽系统生成的用于标识应用的ID，在调用 PUSH API V3 时需要使用。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.appKey}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>SECRET KEY</span>
                    <el-tooltip placement="right">
                      <div slot="content">用于验证API调用的密钥，用于验证调用的合法性。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.secretKey}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>ACCESS ID</span>
                    <el-tooltip placement="right">
                      <div slot="content">信鸽系统生成的ID，需要配置到客户端SDK中。<br>此外，在调用 PUSH API V2 时也需要使用。（ PUSH API V3 中不再使用）</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.accessId}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>ACCESS KEY</span>
                    <el-tooltip placement="right">
                      <div slot="content">信鸽系统生成的客户端鉴权密钥，与ACCESS ID共同验证以确定调用合法。<br>需要配置到客户端SDK中，无法更换。</div>
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="16"><span>{{AndroidForm.accessKey}}</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>客户端SDK</span>
                  </el-col>
                  <el-col :span="16"><span>点击下载</span></el-col>
                </el-row>
              </li>
              <li>
                <el-row>
                  <el-col :span="6">
                    <span>安装文档</span>
                  </el-col>
                  <el-col :span="16"><span>点击查看</span></el-col>
                </el-row>
              </li>
            </ul>
          </el-card>
        </el-col>
        <el-col :span="6">
          <div style="height: 200px;">
            <el-steps v-if="platIndex === '21'" direction="vertical" :active="act_flag">
              <el-step title="选择平台"></el-step>
              <el-step title="填写配置"></el-step>
              <el-step title="安装SDK"></el-step>
            </el-steps>
            <el-steps v-else direction="vertical" :active="act_flag">
              <el-step title="选择平台"></el-step>
              <el-step title="填写配置"></el-step>
              <el-step title="上传证书"></el-step>
              <el-step title="安装SDK"></el-step>
            </el-steps>
          </div>
        </el-col>
      </el-row>
      <!---------- 会话框脚步（步骤不一样显示不一样） ------------>
      <template slot="footer" class="dialog-footer" v-if="ruleForm.platform === 22">
        <template v-if="act_flag !== 3">
          <el-button @click="handleDialogClose">取 消</el-button>
          <el-button v-if="act_flag !== 0" @click="handleChangeBack">上一步</el-button>
          <el-button type="primary" @click="handleChangeNext">下一步</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="handleDialogClose">完成</el-button>
        </template>
      </template>
      <template slot="footer" class="dialog-footer" v-else>
        <template v-if="act_flag !== 2">
          <el-button @click="handleDialogClose">取 消</el-button>
          <el-button v-if="act_flag !== 0" @click="handleChangeBack">上一步</el-button>
          <el-button type="primary" @click="handleChangeNext">下一步</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="handleDialogClose">完成</el-button>
        </template>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import csHeader from '../comm/self/header'
  import tcHeader from '../comm/other/header'
  import { nextPage } from '../../assets/js/index'
  import { APP_TYPE_ARR } from './comm/js/commjs'
  import api from '../../api/url'
  import ajax from '../../api/ajax/mobilePushAjax'
  import { mapMutations, mapGetters } from 'vuex'
  import { Base64 } from 'js-base64'
  import { gatefay } from './comm/js/dict'
  import sysNameObj from '../../sysNameObj'
  export default {
    name: 'push-index',
    components: {
      csHeader,
      tcHeader
    },
    data () {
      let appPackageNameFun = (rule, value, callback) => {
        if (this.ruleForm.platform === 22) {
          callback()
        } else {
          if (!value) {
            return callback(new Error('请输入应用包名'))
          } else {
            callback()
          }
        }
      }
      return {
        tableLoading: true, // 加载过程
        checked: true,
        tentativelyappkey: '', // 创建成功的appkey
        tentatsecretkey: '', // 创建成功的secretkey
        showonebar: false, // 控制提交按钮的显示隐藏
        showtwobar: false, // 控制提交按钮的显示隐藏
        developContent: '', // 开发证书内容
        produceContent: '', // 生产证书内容
        pagesize: 10, // 默认每页数据量
        currentPage: 1, // 当前页码
        totalCount: 0, // 默认数据总数
        ruleForm: {
          appPackageName: '',
          platform: 22,
          regAccount: ''
        },
        rules: {
          appName: [{required: true, message: '请输入应用名称', trigger: 'blur'}],
          appPackageName: [{validator: appPackageNameFun, trigger: 'blur'}],
          appType: [{required: true, message: '请选择所属分类', trigger: 'blur'}]
        },
        AndroidForm: {},
        appTypeArr: APP_TYPE_ARR,
        platIndex: '22',
        dialogVisible: false,
        act_flag: 0,
        sysNameObj: sysNameObj,
        pushIndexData: [
          // {
          //   accessId: '2100319746',
          //   accessKey: 'AA58995FHCAV',
          //   appKey: 'c79af8da9bdcf',
          //   appName: '科蓝',
          //   appPackageName: 'cn.tmf.mobile.iap.mfa',
          //   appType: 1,
          //   id: '1',
          //   platform: 'android',
          //   secretKey: '40c38bf8c6cfcf36a9a40a59e67a2178'
          // },
          //  {
          //   accessId: '2100001088',
          //   accessKey: 'AA2v13G6k4DW',
          //   appKey: 'wqwuficpv2fwe',
          //   appName: 'androidApp推送',
          //   appPackageName: 'cn.tmf.mobile.iap.mfa',
          //   appType: 3,
          //   id: '1',
          //   platform: 'android',
          //   secretKey: '64371bbbf02415bf3d3d6855024fb248'
          // },
           {
            accessId: '2100322623',
            accessKey: 'AA1FU618N5HI',
            appKey: '598cc9271d50d',
            appName: '新闻',
            appPackageName: 'cn.tmf.mobile.iap.mfa',
            appType: 12,
            id: '1',
            platform: 'android',
            secretKey: '93c2303e13f95d6e890b18de32126ab8'
          },
           {
            accessId: '2200257934',
            accessKey: 'IF7E9U92S3ZC',
            appKey: '21ecb5bc6eae7',
            appName: 'iosApp推送',
            appPackageName: '',
            appType: 3,
            id: '1',
            platform: 'ios',
            secretKey: '1b33d7538824e0ff42fc0bcfb60951a3'
          }
          ]
      }
    },
    // 翻译类型
    computed: {
    devTypesDict () {
      return gatefay.appType
    },
    ...mapGetters(['v3platform'])
  },
    methods: {
      ...mapMutations(['v3_updateAppId', 'v3_updateAppTitle', 'v3_updateAppKey', 'v3_updateSecretKey', 'v3_updatePlatform', 'v3_deleteAppId']),
      // 新建应用
      handleAddApply () {
        this.act_flag = 0
        this.dialogVisible = true
      },
      // 当前页数
      handleCurrentChange (val) {
        this.currentPage = val
        this.queryDataList()
      },
      // 每页显示条目个数
      handleSizeChange (val) {
        this.pagesize = val
        this.handleCurrentChange()
      },
      // 点击开发选择文件触发
      developfileChange () {
        let file = document.getElementById('file').files[0]
        const extension = file.name.split('.')[1] === 'pem'
      if (!extension) {
          this.$message({
              message: '上传模板只能是 pem 格式!',
              type: 'err'
            })
            return
      }
      let reader = new FileReader()
        reader.readAsText(file, 'gb2312')
        reader.onload = (evt) => { // 读取完文件之后会回来这里
        let fileString = evt.target.result // 读取文件内容
        this.developContent = fileString
        if (extension && fileString) {
          this.showonebar = true
        }
        }
      },
      // 点击开发上传证书
      requestDevelop () {
        let headersbar = {
             Authorization: 'Basic' + ' ' + Base64.encode(this.tentativelyappkey + ':' + this.tentatsecretkey),
              'Content-Type': 'application/json'
           }
        let Contentbar = {
            certContent: Base64.encode(this.developContent),
            certType: 2
        }
      ajax.post(api.UPLOAD_CERTIFICATE, JSON.stringify(Contentbar), headersbar).then(res => {
          if (res.ret_code === 0 && res.err_msg === '操作成功') {
                  this.$message({
                  message: '上传成功',
                  type: 'success'
                })
            }
          if (res.err_msg !== '操作成功') {
            this.$message.error(res.err_msg)
          }
            }).catch(() => {})
      },
      // 点击生产选择文件触发
      producefileChange () {
        let file = document.getElementById('filebar').files[0]
        const extension = file.name.split('.')[1] === 'pem'
        if (!extension) {
          this.$message({
              message: '上传模板只能是 pem 格式!',
              type: 'err'
            })
            return
      }
        let reader = new FileReader()
        reader.readAsText(file, 'gb2312')
        reader.onload = (evt) => { // 读取完文件之后会回来这里
        let fileString = evt.target.result // 读取文件内容
        this.produceContent = fileString
        if (fileString) {
          this.showtwobar = true
        }
        }
      },
      // 点击生产上传证书
      requestProduce () {
        let headersbar = {
             Authorization: 'Basic' + ' ' + Base64.encode(this.tentativelyappkey + ':' + this.tentatsecretkey),
              'Content-Type': 'application/json'
           }
        let Contentbar = {
            certContent: Base64.encode(this.developContent),
            certType: 1
        }
      ajax.post(api.UPLOAD_CERTIFICATE, JSON.stringify(Contentbar), headersbar).then(res => {
                if (res.ret_code === 0) {
                  this.$message({
                  message: '上传成功',
                  type: 'success'
                })
            }
             if (res.err_msg) {
            this.$message.error(res.err_msg)
          }
            }).catch(() => {})
      },
      // 创建推送
      handleChangeOperate (scope, item) {
        this.v3_updateAppKey(scope.appKey)
        this.v3_updateSecretKey(scope.secretKey)
        this.v3_updatePlatform(scope.platform)
        this.v3_updateAppTitle(scope.appName)
        this.v3_updateAppId(scope.accessId)
        this.v3_deleteAppId(scope.id)
        if (item === 'create') {
          nextPage('/home/notificatioBarMessage')
        } else if (item === 'historical') {
          nextPage('/home/historicalDetails')
        } else {
            if (this.v3platform === 'android') {
                nextPage('/home/applicationConfiguration')
                } else {
                nextPage('/home/applicationaInformation')
            }
        }
      },
      // 选择平台
      selectPlat (index) {
        this.platIndex = index
        this.ruleForm.platform = Number(index)
      },
      // 点击取消
      handleDialogClose () {
        this.dialogVisible = false
        this.platIndex = '22'
        this.ruleForm = {
          platform: 22,
          regAccount: '',
          appPackageName: ''
        }
        this.$refs.ruleForm.clearValidate()
      },
      // 点击上一步
      handleChangeBack () {
        this.act_flag--
      },
      // 点击下一步
      handleChangeNext () {
        if (this.act_flag === 0) {
          this.act_flag++
        } else {
          if (this.act_flag === 1) {
            this.$refs.ruleForm.validate((valid) => {
              if (valid) {
                this.act_flag++
                this.AppCreateFun()
              } else {
                console.log('error submit!!')
                return false
              }
            })
          } else {
            this.act_flag++
          }
        }
      },
      // 新建应用ajax
      AppCreateFun () {
        // 发送ajax请求
        let params = {...this.ruleForm}
        let head = {RegKey: 'i8bwy3VRkDsEo9rqdifnXpA'}
        ajax.post(api.V3_APP_CREATE, params, head).then(res => {
          console.log('25555', res)
          if (res.ret_code === 0 && res.err_msg === '操作成功') {
            this.AndroidForm = res.result
            this.tentativelyappkey = res.result.appKey
            this.tentatsecretkey = res.result.secretKey
            let param = {
              appKey: res.result.appKey,
              accessId: res.result.accessId,
              secretKey: res.result.secretKey,
              accessKey: res.result.accessKey
            }
            this.pushInsertInfo(param)
          }
        if (res.err_msg === 'The app exist already.appName:andriod测试,platform:21,regAccount:') {
            this.$message.error('应用已经存在！')
          }
      }).catch(() => {})
      },
      // 储存数据
      pushInsertInfo (data) {
        let obj = {
          platform: this.ruleForm.platform === 21 ? 'android' : 'ios',
          appName: this.ruleForm.appName,
          appPackageName: this.ruleForm.appPackageName,
          appType: this.ruleForm.appType
        }
        let params = Object.assign(obj, data)
        ajax.post(api.INSERT_PUSH_INFO, params).then(res => {
          if (res.status === '000000' && res.msg === '交易成功') {
            this.queryDataList()
          }
        })
      },
      // 获取应用列表
      queryDataList () {
          //  let pagelistdata = {
          //      pageNo: this.currentPage,
          //      pageSize: this.pagesize
          //    }
          //   ajax.post(api.LIST_PUSH_INFO, pagelistdata).then(res => {
          //   console.log('列表是==', res)
          //    this.pushIndexData = []
          //     this.pushIndexData = res.data.list
          //    console.log('this.pushIndexData', this.pushIndexData)
          //     this.totalCount = res.data.total
          this.totalCount = this.pushIndexData.length
           this.tableLoading = false
        // })
      }
    },
    created () {
      this.queryDataList()
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #push-index
    height: 100%
    width: 100%
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
      margin-bottom: 10px
    .mainconteler
      height: 100%
      width: 100%
      height calc(100% - 120px)
      overflow: auto
      overflow-x hidden
    .box-card
      ul
        li
          line-height 40px
    .plat-list
      overflow hidden
      li
        float left
        width 50%
        padding 10px 0px
        position relative
        .el-radio
          position absolute
          left 0
          top 0
          right 0
          bottom 0
          opacity 0
          z-index -1
        & > span
          display block
          padding 25px 15px 35px
          font-size 14px
          color #333
          line-height 24px
          text-align center
          margin 0 10px
          border 1px solid #eee
          position relative
          transition color .3s linear, border-color .3s linear
          &:after
            content '\e604'
            font-family 'iconfont'
            display block
            font-size 32px
            color #8a8a8a
            margin 3px auto 0
            transition color .3s linear
          &:before
            content '\e8f7'
            font-family 'iconfont'
            position absolute
            right 10px
            bottom 10px
            color #8a8a8a
            font-size 24px
            transition color .3s linear
        &:first-child
          & > span
            margin-left 0
        &:nth-child(2)
          & > span
            &:after
              content '\e615'
        &:last-child
          span
            margin-right 0
        &.active
          span
            color #4093ff
            border 1px solid #4093ff
            &:after
              color #4093ff
            &:before
              color #4093ff
</style>
